import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { Task } from '../task/task.model';

import { ModalDirective } from 'ngx-bootstrap/modal';

import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-course',
  templateUrl: './course.component.html',
  styleUrls: ['./course.component.css',
        '../task/task.component.css',
        '../app.component.css']
})
export class CourseComponent implements OnInit {
    private headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
    url = 'http://edu.xk.com/xkapi'; 
    addOrEdit:string = 'add';

    data = [];
    array = [];

    size: number = 10;    
    index: number;     //要先声明 

    searchCode:string = '';
    id: number = 0;

    name:string = '';

    content:string = '';
    deleteId : number = 0;
    isEmpty:boolean = false;
    /* 分页，start*/
    maxSize: number = 5;
    bigTotalItems: number = 50000; //总数
    bigCurrentPage: number = 1; //当前页
    numPages: number = 0;   //总页数
   
    pageChanged(event: any): void {
      this.bigCurrentPage = event.page;
      this.getList(event.page, 10);
      console.log('Page changed to: ' + event.page);
      console.log('Number items per page: ' + event.itemsPerPage);
    }
    /* 分页，end*/
    constructor(private http: HttpClient){ }

    ngOnInit() {
      this.getList(1,10)  //要this
    }

    getList(pagenumber, pagesize){

        let reqParam = `page=${pagenumber}&size=${pagesize}&name=${this.searchCode}`;
        return this.http.post(`${this.url}/lesson/findAllByQueryAndPage`, reqParam, { 'headers': this.headers} ).subscribe(
          result => {
              if(result) {
                  if (result['status'] == 200) {
                      this.data = result['data'];
                      this.array = this.data['content'];
                      this.bigTotalItems = this.data['totalElements']; //总数
                      this.numPages = this.data['totalPages'];   //总页数
                  } else {
                      console.log(result['desc']);
                  }
              }
          }
      );
    }

    // search
    search() {
        this.bigCurrentPage = 1;
        this.getList(1, 10);
    }
    clear() {
        this.searchCode = '';

        this.search();
    }

    //添加和编辑 提交按钮
    onSubmit(id, name, content, addModal):void {
        let reqUrl = this.addOrEdit === 'add' ? `${this.url}/lesson/add` : `${this.url}/lesson/update`;
        
        if (!( name && content)) {
            this.isEmpty= true;
            return;
        }
        this.isEmpty= false;
        this.http.get(`${reqUrl}?id=${id}&name=${name}&content=${content}`).subscribe(
          result => {
            if(result) {
              if (result['status'] == 200) {
                  this.getList(1, 10); //要this
                  this.bigCurrentPage = 1;
                  addModal.hide();
              } else {
                  console.log(result['desc']);
              }
            }
          }
        );
    }
    ngChangedFn():void {
        this.isEmpty = false;
    }
    //添加
    addNew(addModal) {
        addModal.show();

        this.addOrEdit = 'add';
        this.id = 0;
        this.name = '';
        this.content = '';
    }
    // 编辑 按钮
    edit(item, addModal) {  
        console.log('item:');
        console.log(item);

        addModal.show();
        
        this.addOrEdit = 'edit';
        this.id = item.id;
        this.name = item.name;
        this.content = item.content;
    }
    //删除按钮
    delete(item, deleteModal){  
        deleteModal.show();
        console.log('delete');
        this.deleteId= item.id;
        
    }
    //删除 确认
    deleteConfirm(item,deleteModal) {  
        console.log('item:');
        console.log(item);
        return this.http.get(`${this.url}/lesson/delete?id=${this.deleteId}`).subscribe(
          result => {
              if(result) {
                this.getList(1, 10)  //要this
                this.bigCurrentPage = 1;
                deleteModal.hide();
              } else {
                  console.log(result['desc']);
              }
          }
      );
    }
}
